<template>
  <div :style="{ height: height + 'px' }" class="code-container" ref="container"></div>
</template>

<script>
// import * as monaco from 'monaco-editor';
export default {
  name: 'codeEditor',
  props: {
    opts: {
      type: Object,
      default() {
        return {
          language: 'json',
          theme: 'vs-dark',
          readOnly: false
        };
      }
    },
    code: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 500
    }
  },
  watch: {
    code: {
      handler(n) {
        if (this.showInit) {
          //初次传值初始化一次
          this.init();
          this.showInit = false;
        }
        this.monacoInstance.setValue(n); //剩余全部更新内容
      },
      deep: true
    }
  },
  data() {
    return {
      monacoInstance: null,
      showInit: true
    };
  },
  created() {
    this.init();
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    this.dispose();
  },

  methods: {
    cloneDeep(suggestions) {
      return JSON.parse(JSON.stringify(suggestions));
    },
    dispose() {
      if (this.monacoInstance) {
        if (this.monacoInstance.getModel()) {
          this.monacoInstance.getModel().dispose();
        }
        this.monacoInstance.dispose();
        this.monacoInstance = null;
      }
    },
    init() {
      let that = this;
      this.dispose();
      // 初始化编辑器实例
      let editorConfig = {
        language: 'json',
        theme: 'vs-dark',
        autoIndent: true,
        readOnly: false,
        value: this.code,
        ...this.opts
      };

      this.monacoInstance = monaco.editor.create(this.$refs['container'], editorConfig);
      // 监听编辑器content变化事件
      this.monacoInstance.onDidChangeModelContent(() => {
        let content = this.monacoInstance.getValue();
        this.$emit('contentChange', this.monacoInstance.getValue());
      });
    }
  }
};
</script>
<style lang="scss" scope>
.code-container {
  width: 100%;
  overflow: hidden;
  border: 1px solid #282f3a;
  .monaco-editor .scroll-decoration {
    box-shadow: none;
  }
}
</style>
